package gui;

import enums.PanelsEnum;
import gui.filefilter.XMLFileFilter;
import gui.other.Dimensions;
import gui.other.IntroDialog;
import gui.other.SylogismViewerDialog;
import gui.other.TheoryDialog;
import gui.panel.*;
import j_util.Utiles;
import model.Polisilogismo;
import model.Sylogism;

import javax.help.CSH;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
/*

    This file is part of Logica-Logike.

    Logica-Logike is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Logica-Logike is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Logica-Logike.  If not, see <http://www.gnu.org/licenses/>.

 */
/**
 * @author Jose M. Rozanec;
 * @deprecated;
 */
public class MainFrame3 extends JFrame {
    public static boolean helpInitialized = false;
    private JDialog helpDialog;

    public static JMenuItem getHelpMenuItem(JFrame mainFrame) {
        HelpSet hs;
        HelpBroker hb;
// Find the HelpSet file and create the HelpSet object:
        ClassLoader classLoader = mainFrame.getClass().getClassLoader();
        URL hsURL = null;
        try {
//            hsURL=new File(new File("help/help.hs").getAbsolutePath()).toURI().toURL();//0
//            System.out.println("created==>  "+hsURL.toString());

//            hsURL=new URL((new File(".")).toURI().toURL(), "help/help.hs");//0

//            hsURL=new URL("jar:file:help.jar!/help/help.hs");

//            hsURL=HelpSet.findHelpSet(classLoader,"help/help.hs");//1

//            hsURL=HelpSet.findHelpSet(classLoader,"help.hs");//1

//            classLoader=ClassForClassLoader.class.getClassLoader();
//            hsURL = new URL("jar:file:help.jar!/LogicaHelp.hs");

//            hsURL=HelpSet.findHelpSet(classLoader,"/../help/help.hs");//1

//            URL url = new URL((new File("help/html/clasica/introduccion.html")).toURI().toURL(), "help/html/clasica/introduccion.html");


            File filea = (new File("help/html/clasica/introduccion.html"));
            URL url = filea.toURL();
            URI uri = new URI(url.toString().replaceFirst("/", ""));
            java.awt.Desktop.getDesktop().browse(url.toURI());

            hs = new HelpSet(null, hsURL);

        } catch (Exception ee) {
// Say what the exception really is
            System.out.println("Message: " + ee.getMessage());//todo delete
            if (hsURL != null) {
                System.out.println("HelpSet " + hsURL.toString() + " not found");//todo delete
            } else {
                System.out.println("hsURL is null");//todo delete
            }
            return null;
        }
// Create a HelpBroker object:
        hb = hs.createHelpBroker();
        hb.enableHelpKey(mainFrame.getRootPane(), "overview", hs);
        JMenuItem helpMenuItem = new JMenuItem("Ayuda");
        helpMenuItem.addActionListener(new CSH.DisplayHelpFromSource(hb));
        return helpMenuItem;
    }

//    public JMenuItem getHelp(String jarPath) {
//        HelpUtil helpUtil = new HelpUtil();
//        helpUtil.getHelpSet(jarPath);
//        return new JMenuItem("Ayuda");
//    }
//
//    public JMenuItem getHelpAction(String hsPath) {
//        HelpAction.initialize(hsPath);
//        Action gsAction = new HelpAction("Help", "gs.top");
//        return new JMenuItem(gsAction);
//    }

    public JMenuItem getHelpDialog() {
        File file = new File("/help/html/clasica/introduccion.html");
        JMenuItem menuItem = new JMenuItem("Help");
        try {
            final JEditorPane editorPane = new JEditorPane(file.toURI().toURL());
            editorPane.setEditable(false);
//            editorPane.addHyperlinkListener(new HyperlinkListener(){
//                public void hyperlinkUpdate(HyperlinkEvent e) {
//
//                }
//            });
            menuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (helpDialog == null) {
                        helpDialog = new JDialog(MainFrame3.this, "Help");
                        helpDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        helpDialog.add(editorPane);
                        helpDialog.setPreferredSize(new Dimension(500, 500));
                    }
                    if (!helpInitialized) {
                        helpDialog.setVisible(true);
                    }
                }
            });
        } catch (MalformedURLException e) {
            System.out.println("Failed to build URL");
        } catch (IOException e) {
            System.out.println("IOException - MainFrame3 getHelpDialog");
        }
        return menuItem;
    }

    public static void main(String[] args) {
        final JFileChooser openFileChooser = new JFileChooser();
        final JFileChooser saveFileChooser = new JFileChooser();
        final Sylogism[] sylogism = new Sylogism[]{new Sylogism()};//todo ver como afecta el final los cambios dentro de los paneles
        final Polisilogismo[] polisilogismo = new Polisilogismo[]{new Polisilogismo()};//todo ver como afecta el final los cambios dentro de los paneles
        final PanelsEnum[] current = new PanelsEnum[]{PanelsEnum.OPOSICION};
        final JPanel cardsPanel = new JPanel(new CardLayout());
        final SilogismoPanel silogismoPanel = new SilogismoPanel();
        silogismoPanel.setSylogism(sylogism[0]);
        final PolisilogismoPanel polisilogismoPanel = new PolisilogismoPanel();
        polisilogismoPanel.setPolisilogismo(polisilogismo[0]);

        cardsPanel.add(new OposicionPanel(), PanelsEnum.OPOSICION.toString());
        cardsPanel.add(silogismoPanel, PanelsEnum.SILOGISMO.toString());
        cardsPanel.add(polisilogismoPanel, PanelsEnum.POLISILOGISMO.toString());
        cardsPanel.add(new TruthTablePanel(), PanelsEnum.TABLA_VERDAD.toString());

        final CardLayout cardLayout = (CardLayout) (cardsPanel.getLayout());
        final MainFrame3 mainFrame = new MainFrame3();
        JMenuBar menuBar = new JMenuBar();
        JMenu logicaClasicaMenu = new JMenu("Logica clasica");
        JMenu logicaMatematicaMenu = new JMenu("Logica matematica");
        JMenu helpMenu = new JMenu("Ayuda");

        final JMenuItem toXMLMenuItem = new JMenuItem("Guardar como");
        toXMLMenuItem.setIcon(Utiles.createImageIcon("/gui/images/other/saveAs.png"));
        toXMLMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                saveFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                boolean violation = false;
                switch (current[0]) {
                    case POLISILOGISMO:
                        if (!polisilogismo[0].initialSylogismWasSet()) {
                            JOptionPane.showMessageDialog(mainFrame, "No se puede guardar un polisilogismo vacio!", "", JOptionPane.WARNING_MESSAGE);
                            violation = true;
                        }
                        break;
                    case SILOGISMO:
                        if (!sylogism[0].isComplete()) {
                            JOptionPane.showMessageDialog(mainFrame, "No se puede guardar un silogismo vacio!", "", JOptionPane.WARNING_MESSAGE);
                            violation = true;
                        }
                        break;
                }
                if (!violation) {
                    String path = "";
                    int state = saveFileChooser.showSaveDialog(mainFrame);
                    if (state == JFileChooser.APPROVE_OPTION) {
                        path = saveFileChooser.getSelectedFile().getPath();
                        if (!path.endsWith(".xml")) {
                            path = path.concat(".xml");
                        }
                        File file = new File(path);
                        if (file.exists()) {
                            JOptionPane.showMessageDialog(mainFrame, "El archivo seleccionado ya existe!", "", JOptionPane.WARNING_MESSAGE);
                        } else {
                            try {
                                RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
                                switch (current[0]) {
                                    case POLISILOGISMO:
                                        randomAccessFile.writeUTF(polisilogismo[0].toXML());
                                        break;
                                    case SILOGISMO:
                                        randomAccessFile.writeUTF(sylogism[0].toXML());
                                        break;
                                }
                            } catch (FileNotFoundException e1) {
                                e1.printStackTrace();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        toXMLMenuItem.setEnabled(false);

        final JMenuItem fromXMLMenuItem = new JMenuItem("Abrir");
        fromXMLMenuItem.setIcon(Utiles.createImageIcon("/gui/images/other/open.png"));
        fromXMLMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String path = "";
                openFileChooser.setFileFilter(new XMLFileFilter());
                int state = openFileChooser.showOpenDialog(mainFrame);
                if (state == JFileChooser.APPROVE_OPTION) {
                    path = openFileChooser.getSelectedFile().getPath();
                    File file = new File(path);

                    try {
                        RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");
                        String xml = randomAccessFile.readUTF();
                        switch (current[0]) {
                            case POLISILOGISMO:
                                if (xml.startsWith(Polisilogismo.openTag())) {
                                    polisilogismo[0] = Polisilogismo.parseXML(xml);
                                    polisilogismoPanel.setPolisilogismo(polisilogismo[0]);
                                } else {
                                    if (xml.startsWith(Sylogism.openTag())) {
                                        polisilogismo[0] = new Polisilogismo();
                                        polisilogismo[0].setInitialSylogism(Sylogism.parseXML(xml));
                                        polisilogismoPanel.setPolisilogismo(polisilogismo[0]);
                                    } else {
                                        JOptionPane.showMessageDialog(mainFrame, "El archivo abierto no puede traducirse a un polisilogismo.");
                                    }
                                }
                                break;
                            case SILOGISMO:
                                if (xml.startsWith(Sylogism.openTag())) {
                                    sylogism[0] = Sylogism.parseXML(xml);
                                    silogismoPanel.setSylogism(sylogism[0]);
                                } else {
                                    if (xml.startsWith(Polisilogismo.openTag())) {
                                        SylogismViewerDialog sylogismViewerDialog = new SylogismViewerDialog(Polisilogismo.parseXML(xml).getIterator());
                                        Utiles.centerDialog(sylogismViewerDialog);
                                        sylogismViewerDialog.setSize(337, 160);
                                        sylogismViewerDialog.setResizable(false);
                                        sylogismViewerDialog.setModal(true);
                                        sylogismViewerDialog.setVisible(true);
                                        if (sylogismViewerDialog.accepted()) {
                                            sylogism[0] = sylogismViewerDialog.getSylogism();
                                            silogismoPanel.setSylogism(sylogism[0]);
                                        }
                                    } else {
                                        JOptionPane.showMessageDialog(mainFrame, "El archivo abierto no puede traducirse a un silogismo.");
                                    }
                                }
                                break;
                        }
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
        fromXMLMenuItem.setEnabled(false);

        JMenuItem oposicionMenuItem = new JMenuItem("Cuadro de oposicion");
        oposicionMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardsPanel, PanelsEnum.OPOSICION.toString());
                current[0] = PanelsEnum.OPOSICION;
                toXMLMenuItem.setEnabled(false);
                fromXMLMenuItem.setEnabled(false);
            }
        });

        JMenuItem silogismoMenuItem = new JMenuItem("Silogismo");
        silogismoMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardsPanel, PanelsEnum.SILOGISMO.toString());
                current[0] = PanelsEnum.SILOGISMO;
                toXMLMenuItem.setEnabled(true);
                fromXMLMenuItem.setEnabled(true);
            }
        });

        JMenuItem poliSilogismoMenuItem = new JMenuItem("Polisilogismo");
        poliSilogismoMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardsPanel, PanelsEnum.POLISILOGISMO.toString());
                current[0] = PanelsEnum.POLISILOGISMO;
                toXMLMenuItem.setEnabled(true);
                fromXMLMenuItem.setEnabled(true);
            }
        });

        JMenuItem tablasDeVerdadMenuItem = new JMenuItem("Tabla de verdad");
        tablasDeVerdadMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardsPanel, PanelsEnum.TABLA_VERDAD.toString());
                current[0] = PanelsEnum.TABLA_VERDAD;
                toXMLMenuItem.setEnabled(false);
                fromXMLMenuItem.setEnabled(false);
            }
        });

        JMenuItem helpMenuItem = new JMenuItem("Teoria");
        helpMenuItem.setIcon(Utiles.createImageIcon("/gui/images/other/help.png"));
        helpMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TheoryDialog theoryDialog = new TheoryDialog();
                theoryDialog.setTitle("Teoria");
                theoryDialog.setIconImage(Utiles.createImageIcon("/gui/images/other/help.png").getImage());
                theoryDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                theoryDialog.setMinimumSize(new Dimension(600, 600));
                theoryDialog.setPreferredSize(new Dimension(600, 600));
                theoryDialog.setResizable(false);
                theoryDialog.setModal(true);
                theoryDialog.setVisible(true);
            }
        });
//        helpMenu.add(mainFrame.getHelpAction("/help/help.hs"));
//        helpMenu.add(mainFrame.getHelpDialog());

        JMenuItem aboutMenuItem = new JMenuItem("Acerca de...");
        aboutMenuItem.setIcon(Utiles.createImageIcon("/gui/images/other/information.png"));
        aboutMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog();
                Dimension frameDimension = new Dimension(650, 680);
                dialog.setContentPane(new AboutPanel());
                dialog.setTitle("Acerca de...");
                dialog.setIconImage(Utiles.createImageIcon("/gui/images/other/information.png").getImage());
                dialog.setPreferredSize(frameDimension);
                dialog.setSize(frameDimension);
                dialog.setMinimumSize(frameDimension);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setResizable(false);
                Utiles.centerDialog(dialog);
                dialog.setModal(true);
                dialog.setVisible(true);
//                AboutDialog aboutDialog = new AboutDialog();
//                aboutDialog.setResizable(false);
//                Utiles.centerDialog(aboutDialog);
//                aboutDialog.setModal(true);
//                aboutDialog.setVisible(true);
            }
        });

        logicaClasicaMenu.add(fromXMLMenuItem);//todo ver problemas con Premisa
        logicaClasicaMenu.add(toXMLMenuItem);
        logicaClasicaMenu.add(oposicionMenuItem);
        logicaClasicaMenu.add(silogismoMenuItem);
        logicaClasicaMenu.add(poliSilogismoMenuItem);

        logicaMatematicaMenu.add(tablasDeVerdadMenuItem);

        menuBar.add(logicaClasicaMenu);
        menuBar.add(logicaMatematicaMenu);

        helpMenu.add(helpMenuItem);
        helpMenu.add(aboutMenuItem);
        menuBar.add(helpMenu);

        mainFrame.setJMenuBar(menuBar);

        mainFrame.add(cardsPanel);
        mainFrame.setTitle("Logica 2.0");
        mainFrame.setIconImage(Utiles.createImageIcon("/gui/images/other/logicaIcon.png").getImage());
        mainFrame.setSize(Dimensions.FRAME_WIDTH, Dimensions.FRAME_HEIGHT);
        mainFrame.setResizable(false);
        Utiles.centerFrame(mainFrame);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        IntroDialog introDialog = new IntroDialog("../gui/images/Logica.png");
        introDialog.run();

        mainFrame.setVisible(true);
    }
}
